package com.opensourceedge.phonebook.cli;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import com.opensourceedge.phonebook.api.Contact;
import com.opensourceedge.phonebook.api.FileStore;
import com.opensourceedge.phonebook.api.Store;

public class SearchContactCommand implements Command {

	final String COMMAND = "ser";
	ArrayList<Contact> searchResult;
	public static String helpText;
	String tag;

	public SearchContactCommand() {
		searchResult = new ArrayList<Contact>();
		tag = null;
		
		helpText="'"+COMMAND+"' to Search Contact.";
	}

	@Override
	public void execute() {
		// System.out.println("inside modifyContactcommand");
		Store cs = new FileStore("/contacts.txt");
		// gets input from command.
		System.out.print("Enter Search tag:");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			tag = br.readLine();
			searchResult = cs.search(tag);
			this.printSearchResult();
			
		} catch (Exception e) {
			System.out.println("<ERROR> Error while executing Search");
		}
	}

	private void printSearchResult() {
		for (int i = 0; i < searchResult.size(); i++) {
			if(i % 5==0 || i==0){
				System.out.println("ID->"+"Contact ID" + "\t"
						+"FN->"+ "First Name" + "\t"
						+"LN->"+ "Last Name" + "\t"
						+"MP->"+ "Mobile Phone" + "\t"
						+"WP->"+ "Work Phone" + "\t"
						+"CN->"+ "Company Name" + "\t"
						+"SN->"+ "Street Name" + "\t"
						+"BN->"+ "Building Number" + "\t"
						+"CT->"+ "City" + "\t"
						+"ST->"+ "State" + "\t"
						+"ZC->"+ "Zip Code" + "\t\n"
						);
			}
			System.out.println("ID->"+searchResult.get(i).getContactID() + "\t"
					+"FN->"+ searchResult.get(i).getFirstName() + "\t"
					+"LN->"+ searchResult.get(i).getLastName() + "\t"
					+"MP->"+ searchResult.get(i).getMobilePhone() + "\t"
					+"WP->"+ searchResult.get(i).getWorkPhone() + "\t"
					+"CN->"+ searchResult.get(i).getCompanyName() + "\t"
					+"SN->"+ searchResult.get(i).getStreetName() + "\t"
					+"BN->"+ searchResult.get(i).getBuildingNumber() + "\t"
					+"CT->"+ searchResult.get(i).getCity() + "\t"
					+"ST->"+ searchResult.get(i).getState() + "\t"
					+"ZC->"+ searchResult.get(i).getZipCode() + "\t\n"
					);
		}
		System.out.println(searchResult.size()+" result found.");
	}


	@Override
	public String getCommandCode() {
		return COMMAND;
	}

	@Override
	public String getCommandHelpText() {
		return helpText;
	}
}
